package org.example.managementsystem.controller;

import org.example.managementsystem.model.Person;
import org.example.managementsystem.model.User;
import org.example.managementsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/auth")
public class UserController {
    private final UserService userService;


    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody Map<String, String> loginRequest) {
        String username = loginRequest.get("username");
        String password = loginRequest.get("password");
        String role = loginRequest.get("role");
        
        if (username == null || password == null || role == null) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "用户名、密码和角色不能为空");
            return ResponseEntity.badRequest().body(response);
        }
        
        User user = userService.login(username, password, role);

        if (user != null) {
            return ResponseEntity.ok(user);
        } else {
            Map<String, String> response = new HashMap<>();
            response.put("message", "用户名或密码错误，或者所选角色不匹配");
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
        }
    }

    /**
     * 重置用户密码
     */
    @PostMapping("/reset-password")
    public ResponseEntity<?> resetPassword(@RequestBody Map<String, String> request) {
        String jobNumber = request.get("jobNumber");
        
        if (jobNumber == null) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "工号不能为空");
            return ResponseEntity.badRequest().body(response);
        }
        
        try {
            // 生成6位随机密码
            String newPassword = generateRandomPassword();
            
            // 更新用户密码
            User user = userService.getUserByJobNumber(jobNumber);
            if (user == null) {
                Map<String, String> response = new HashMap<>();
                response.put("message", "用户不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(response);
            }
            
            user.setPassword(newPassword);
            userService.updateUser(user);
            
            Map<String, String> response = new HashMap<>();
            response.put("message", "密码重置成功");
            response.put("newPassword", newPassword);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, String> response = new HashMap<>();
            response.put("message", "密码重置失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 生成6位随机密码
     */
    private String generateRandomPassword() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder password = new StringBuilder();
        java.util.Random random = new java.util.Random();
        
        for (int i = 0; i < 6; i++) {
            password.append(chars.charAt(random.nextInt(chars.length())));
        }
        
        return password.toString();
    }
}